package com.tanhua.admin.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.commons.utils.PercentUtil;
import com.tanhua.dubbo.db.api.UserApi;
import com.tanhua.model.db.Analysis;
import com.tanhua.model.mongo.MessageAn;

import com.tanhua.model.vo.DashboardVo;

import com.tanhua.model.vo.Summary;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DashboardService {

    @Autowired
    private AnalysisMapper analysisMapper;

    @Autowired
    LogMapper logMapper;

    @DubboReference
    private UserApi userApi;


    public Summary summary() {
        //获取时间
        String todayStr = new SimpleDateFormat ("yyyy-MM-dd").format (new Date ());
        String yesterdayStr = DateUtil.yesterday ().toString ("yyyy-MM-dd"); //工具类
        //1.1 新注册用户数
        Integer logNum = logMapper.queryByTypeAndLogTime ("0102", todayStr);
        //1.2 活跃用户数
        Integer actNum = logMapper.queryByLogTime (todayStr);
        //1.3 登陆次数
        Integer regNum = logMapper.queryByTypeAndLogTime ("0101", todayStr);
        //1.4 次日留存用户数
        Integer mumRetention1d = logMapper.queryNumRetention1d (todayStr, yesterdayStr);

        //构造返回数据
        Summary summary = new Summary ();
        summary.setNewUsersToday (logNum);//今日新增用户
        //昨日新增用户, 新增用户涨跌率
        Integer yesterdayRgNum = logMapper.queryByTypeAndLogTime ("0102", yesterdayStr);
        if (logNum < yesterdayRgNum) {
            summary.setLoginTimesTodayRate (-Integer.valueOf (PercentUtil.getAnalysisData (logNum, yesterdayRgNum)));
        } else {
            summary.setLoginTimesTodayRate (Integer.valueOf (PercentUtil.getAnalysisData (logNum, yesterdayRgNum)));
        }


        summary.setActiveUsersToday (actNum);//今日活跃用户
        Integer yesterdayLog = logMapper.queryByLogTime (yesterdayStr);
        if (actNum < yesterdayLog) {
            summary.setActiveUsersTodayRate (-Integer.valueOf (PercentUtil.getAnalysisData (actNum, yesterdayLog)));
        } else {
            summary.setActiveUsersTodayRate (Integer.valueOf (PercentUtil.getAnalysisData (actNum, yesterdayLog)));
        }

        //活跃用户涨跌率


        summary.setLoginTimesToday (regNum);//今日登录次数
        Integer yesterdayReg = logMapper.queryByTypeAndLogTime ("0101", yesterdayStr);
        if (regNum < yesterdayReg) {
            summary.setLoginTimesTodayRate (-Integer.valueOf (PercentUtil.getAnalysisData (regNum, yesterdayReg)));
        } else {
            summary.setLoginTimesTodayRate (Integer.valueOf (PercentUtil.getAnalysisData (regNum, yesterdayReg)));
        }


        Integer count = userApi.count ();
        summary.setCumulativeUsers (count);//累计用户

        String lastWeek = DateUtil.lastWeek ().toString ("yyyy-MM-dd");
        Integer passWeek = logMapper.queryActivePass (todayStr,lastWeek);
        summary.setActivePassWeek (passWeek);//过去7天活跃用户

        String lastMonth = DateUtil.lastMonth ().toString ("yyyy-MM-dd");
        Integer activePassMonth = logMapper.queryActivePass ( todayStr,lastMonth);
        summary.setActivePassMonth (activePassMonth);//过去30天新增用户

        return summary;
    }



   /* public AnalysisVo summary() throws ParseException {

        System.out.println("ParseException");
        //累计用户总数
        Integer cumulativeUser = logMapper.queryCumulativeUsers();
        System.out.println(cumulativeUser + "========" + cumulativeUser);

        //获取当日时间
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //获取昨日时间
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");//工具类


        //根据日期查询统计表数据是否存在
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(today);
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        qw.eq("record_date", today);
        Analysis analysis = analysisMapper.selectOne(qw);

        //根据当天时间获取7天以前的日期,并获得用户活跃数
        String daysAgo = DateUtil.offsetDay(recordDate, -7).toString("yyyy-MM-dd");
        Integer activePassWeek = logMapper.queryActivePass(today, daysAgo);
        System.out.println("7天用户活跃数:==========" + activePassWeek);
        //根据当天日期获取30天前的日期,并获得用户活跃数
        String day = DateUtil.offsetDay(recordDate, -30).toString("yyyy-MM-dd");
        Integer activePassMonth = logMapper.queryActivePass(today, day);
        System.out.println("30天用户活跃数:==========" + activePassMonth);

        //构造返回值
        AnalysisVo vo = new AnalysisVo();

        vo.setCumulativeUsers(cumulativeUser);
        vo.setActivePassMonth(activePassMonth);
        vo.setActivePassWeek(activePassWeek);
        if (analysis != null) {
            vo.setNewUsersToday(analysis.getNumRegistered());
            vo.setLoginTimesToday(analysis.getNumLogin());
            vo.setActiveUsersToday(analysis.getNumActive());
        }
        // 百分比们
        // 1.今日活跃用户涨跌率，单位百分数

       // //1.1昨日活跃数
       // Integer yestActive = logMapper.queryByLogTime(yesterday);
       //
       // int yestAct = 0;
       // if (yestActive != null) {
       //     yestAct = yestActive;
       // }
//
       // //1.2 今日活跃数
       // Integer todayActive = logMapper.queryByLogTime(today);
//
       // int todayAct = 0;
       //
       // if (todayActive != null) {
       //     todayAct = todayActive;
       // }
       //
       //
       // double count1=0.0;
       // //判断并赋值
       // if (yestAct == 0 && todayAct == 0) {
       //     vo.setActiveUsersTodayRate(0);
       // } else if (yestAct == 0 && todayAct != 0) {
       //     count1=todayAct*100;
       //
       // } else if (yestAct != 0 && todayAct == 0){
       //     count1=- todayAct*100;
       // }else {
       //     count1 = (todayAct - yestAct) / yestAct;
       //
       //
       //     }
       // System.out.println("百分比" + count1);
       // Integer value = Integer.valueOf((int) count1);
       // vo.setActiveUsersTodayRate(value);
//
//
        // 今日登录次数涨跌率，单位百分数
        // vo.setLoginTimesTodayRate(0);

        // //今日新增用户涨跌率，单位百分数
        // vo.setNewUsersTodayRate(0);

        return vo;

    }
*/
    /**
     * @param sd
     * @param ed
     * @param type * 新增、活跃用户、次日留存率
     *             * sd	 开始时间
     *             * ed   结束时间
     *             * type 101 新增 102 活跃用户 103 次日留存率
     * @return
     */
    public DashboardVo users(String sd, String ed, Integer type) {
        if (type == 101) {
            Date StartDate = new Date (Long.parseLong (sd));//开始日期
            Date EndDate = new Date (Long.parseLong (ed));//结束日期
            ArrayList<MessageAn> thisYear = getMessageAns (StartDate, EndDate);
            //去年时间
            Date lastYearSt = getLastYear (StartDate);
            Date lastYearEnd = getLastYear (EndDate);
            ArrayList<MessageAn> lastList = this.getMessageAns (lastYearSt, lastYearEnd);
            DashboardVo vo = new DashboardVo ();
            vo.setThisYear (thisYear);//今年选择的时间
            vo.setLastYear (lastList);//去年选择的时间
            return vo;
        } else if (type == 102) {//活跃用户
            Date startDate = new Date (Long.parseLong (sd));//开始日期
            Date endDate = new Date (Long.parseLong (ed));//结束日期
            ArrayList<MessageAn> thisYear = getActiveNum (startDate, endDate);
            //去年时间
            Date lastYearSt = getLastYear (startDate);
            Date lastYearEnd = getLastYear (endDate);
            //去年活跃用户
            ArrayList<MessageAn> lastYear = this.getActiveNum (lastYearSt, lastYearEnd);
            DashboardVo vo = new DashboardVo ();
            vo.setThisYear (thisYear);//今年选择的时间
            vo.setLastYear (lastYear);//去年选择的时间
            return vo;
        } else {
            Date startDate = new Date (Long.parseLong (sd));//开始日期
            Date endDate = new Date (Long.parseLong (ed));//结束日期
            ArrayList<MessageAn> thisYear = getMumRetention1d (startDate, endDate);
            //去年时间
            Date lastYearSt = getLastYear (startDate);
            Date lastYearEnd = getLastYear (endDate);
            //去年活跃用户
            ArrayList<MessageAn> lastYear = this.getMumRetention1d (lastYearSt, lastYearEnd);
            DashboardVo vo = new DashboardVo ();
            vo.setThisYear (thisYear);//今年选择的时间
            vo.setLastYear (lastYear);//去年选择的时间
            return vo;
        }
        //logMapper.queryMumRetention1d
    }

//留存用户

    private ArrayList<MessageAn> getMumRetention1d(Date startDate, Date endDate) {
        ArrayList<MessageAn> thisYear = new ArrayList<>();
        List<DateTime> list = DateUtil.rangeToList (startDate, endDate, DateField.DAY_OF_YEAR);
        for (DateTime dateTime : list) {
            String todayStr = new SimpleDateFormat ("yyyy-MM-dd").format (dateTime);//当天
            String preDateByDate = getPreDateByDate (todayStr);//前一天
            Integer actNum = logMapper.queryNumRetention1d (todayStr, preDateByDate);
            MessageAn messageAn = new MessageAn ();
            messageAn.setAmount (actNum);
            //  messageAn.setTitle (list.indexOf (dateTime) + "");
            String format = new SimpleDateFormat ("yyyy-MM-dd").format (dateTime);
            messageAn.setTitle (format);
            thisYear.add (messageAn);
        }
        return thisYear;
    }


    //活跃用户
    private ArrayList<MessageAn> getActiveNum(Date startDate, Date endDate) {
        ArrayList<MessageAn> thisYear = new ArrayList<> ();
        List<DateTime> list = DateUtil.rangeToList (startDate, endDate, DateField.DAY_OF_YEAR);
        for (DateTime dateTime : list) {
            String todayStr = new SimpleDateFormat ("yyyy-MM-dd").format (dateTime);
            Integer logNum = logMapper.queryByLogTime (todayStr);
            MessageAn messageAn = new MessageAn ();
            messageAn.setAmount (logNum);
            String format = new SimpleDateFormat ("yyyy-MM-dd").format (dateTime);
            messageAn.setTitle (format);
            thisYear.add (messageAn);
        }
        return thisYear;
    }

    //登录人数
    private ArrayList<MessageAn> getMessageAns(Date startDate, Date endDate) {
        ArrayList<MessageAn> objects = new ArrayList<> ();
        List<DateTime> list = DateUtil.rangeToList (startDate, endDate, DateField.DAY_OF_YEAR);
        for (DateTime dateTime : list) {
            String todayStr = new SimpleDateFormat ("yyyy-MM-dd").format (dateTime);
            Integer logNum = logMapper.queryByTypeAndLogTime ("0102", todayStr);
            MessageAn messageAn = new MessageAn ();
            messageAn.setAmount (logNum);
            String format = new SimpleDateFormat ("yyyy-MM-dd").format (dateTime);
            messageAn.setTitle (format);
            objects.add (messageAn);
        }
        return objects;
    }

    //获取去年时间的工具
    public static Date getLastYear(Date date) {
        Calendar calendar = Calendar.getInstance ();
        calendar.setTime (date);
        calendar.add (Calendar.YEAR, -1);//当前时间减去一年，即一年前的时间
        return calendar.getTime ();//获取一年前的时间，或者一个月前的时间

    }

    public static String getPreDateByDate(String strData) {
        String preDate = "";
        Calendar c = Calendar.getInstance ();
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse (strData);
        } catch (java.text.ParseException e) {
            e.printStackTrace ();
        }

        c.setTime (date);
        int day1 = c.get (Calendar.DATE);
        c.set (Calendar.DATE, day1 - 1);
        preDate = sdf.format (c.getTime ());
        return preDate;
    }

}
